package com.system.template.core.pdf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfBuilder extends PdfPageEventHelper {

	private static final Logger LOGGER = LoggerFactory.getLogger(PdfBuilder.class);

	private PdfWatermark pdfWatermark;

	public PdfBuilder() {
		super();
	}

	public PdfBuilder(PdfWatermark pdfWatermark) {
		super();
		this.pdfWatermark = pdfWatermark;
	}

	// 当当前页面开始加载时，触发(页眉)
	@Override
	public void onStartPage(PdfWriter writer, Document document) {
		super.onStartPage(writer, document);
	}

	// 当当前页面初始化完成，切入document之前触发(页脚)
	@Override
	public void onEndPage(PdfWriter writer, Document document) {
		Rectangle rect = new Rectangle(document.getPageSize().getWidth(), 25, 0, 0);
		// ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
		// new Phrase(String.format("      ", writer.getPageNumber())), (rect.getLeft() + rect.getRight()) / 2,
		// rect.getBottom() - 18, 0);
		ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
				new Phrase(String.format("- %d -", writer.getPageNumber())), 
				(rect.getLeft() + rect.getRight()) / 2,
				rect.getBottom() - 18,
				0);
		//System.out.println("page number: " + writer.getPageNumber());



		if (pdfWatermark != null && pdfWatermark.getType().intValue() == 0) {
			try {
				Image img = Image.getInstance(pdfWatermark.getPath());
				float rdm = (float) (Math.random() * 100);
				// 旋转 角度
				img.setRotationDegrees(rdm);
				// X、Y的间距
				img.setAbsolutePosition(pdfWatermark.getAbsoluteX() + rdm, pdfWatermark.getAbsoluteY() + rdm);
				if (pdfWatermark.getWidth() != null && pdfWatermark.getHeight() != null) {
					// 自定义水印的大小
					img.scaleAbsolute(pdfWatermark.getWidth(), pdfWatermark.getHeight());
				}
				//document.add(img);
				PdfContentByte pcb = writer.getDirectContent();
				pcb.addImage(img);

			} catch (Exception e) {
				LOGGER.error("添加水印异常: " + e.getMessage());
			}
		}
	}
}